<template>
  <view class="table-code-draw">
    <canvas
      v-for="(item, index) in groups"
      :key="index"
      :canvas-id="`table-code${index}`"
      :style="{'width':`${width}rpx`,'height':`${item.height}rpx`}"
      class="code-img"
    ></canvas>
  </view>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      width: 750,
      height: 0,
      groups: [],
      lineSpace: 5,
      groupNameHeight: 25
    };
  },
  methods: {
    draw(data) {
      const systemInfo = uni.getSystemInfoSync();
      const screenWidth = systemInfo.screenWidth; // 屏幕宽度
      const codeWidth = screenWidth / 2; // 二维码宽度
      this.groups = this.data.map(v => {
        const codeNum = v.tables.length; // 二维码个数
        const rowNum = Math.ceil(codeNum / 2); // 行数
        const height =
          rowNum * (this.width / 2 + (this.lineSpace / screenWidth) * 750) +
          (this.groupNameHeight / screenWidth) * 750; // canvas高度;
        const canvasHeight = rowNum * codeWidth + this.groupNameHeight + 100;
        return { ...v, height: height, canvasHeight: canvasHeight };
      });
      this.$nextTick(async () => {
        await this.drawGroupCode(this.groups);
      });
    },
    drawCode(group, index) {
      const systemInfo = uni.getSystemInfoSync();
      const screenWidth = systemInfo.screenWidth; // 屏幕宽度
      const codeWidth = screenWidth / 2; // 二维码宽度
      return new Promise((resolve, reject) => {
        let context = uni.createCanvasContext(`table-code${index}`);
        let codeNum = 0; // 二维码个数
        let x = 0;
        let y = 0;
        context.save();
        context.setFillStyle("#ffffff");
        context.fillRect(0, 0, screenWidth, group.canvasHeight);
        context.restore();
        context.setFontSize(20);
        context.textAlign = "center";
        context.fillText(group.name, codeWidth, 20);
        group.tables.forEach((table, tIndex) => {
          codeNum++;
          const rowNum = Math.floor((codeNum - 1) / 2); // 行数
          x = codeNum % 2 === 0 ? codeWidth : 0; // 二维码x坐标
          y = rowNum * (codeWidth + this.lineSpace) + this.groupNameHeight; // 二维码y坐标
          context.drawImage(table.tableCode, x, y, codeWidth, codeWidth);
          context.setFontSize(20);
          context.textAlign = "center";
          context.fillText(
            table.tableNo,
            ((codeNum - 1) % 2) * codeWidth + codeWidth / 2,
            y + codeWidth
          );
        });
        context.draw();
        this.$nextTick(() => {
          setTimeout(() => {
            this.saveOne({ canvasId: `table-code${index}` })
              .then(() => {
                resolve();
              })
              .catch(() => {
                reject();
              });
          }, 750);
        });
      });
    },
    async drawGroupCode(groups) {
      let isError = false;
      for (let index = 0; index < groups.length; index++) {
        const group = groups[index];
        this.$showLoading(`正在保存第${index + 1}/${groups.length}份`);
        try {
          await this.drawCode(group, index);
        } catch (error) {
          isError = true;
        }
        if (index == groups.length - 1) {
          this.$hideLoading();
          this.groups = [];
          this.$nextTick(() => {
            this.$emit("finish");
          });

          if (!isError) {
            this.$toast(`成功保存${index + 1}份图片到相册`);
          } else {
            this.$toast(`保存失败`);
          }
        }
      }
    },
    canvasToTempFilePath(config) {
      return new Promise((reslove, reject) => {
        uni.canvasToTempFilePath({
          canvasId: config.canvasId,
          success: res => {
            reslove(res);
          },
          fail: error => {
            reject(error);
          }
        });
      });
    },
    saveImageToPhotosAlbum(config) {
      return new Promise((reslove, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: config.filePath, //保存的位置
          success: res => {
            reslove(res);
          },
          fail: error => {
            reject(error);
          }
        });
      });
    },
    async saveOne(config) {
      let res = await this.canvasToTempFilePath(config);
      await this.saveImageToPhotosAlbum({
        filePath: res.tempFilePath
      });
    }
  }
};
</script>

<style lang="scss">
.table-code-draw {
  height: 0;
  overflow: hidden;
}
</style>
